package com.iamteer.day07;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
主要回顾：xPath
	方法：
		List<Node> selectNodes("expression");	//多个节点
		Node selectSingleNode("expression");	//单个节点
		
	表达式：
		/		绝对路径
		//		相对路径
		*		通配符
		[]		指定元素
		@		指定属性
		and		与关系
		text()	文本
		
 */
public class Learn_xPath {

	public static void main(String[] args) {
		try {

			test1();
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void test1() {
		Document doc;
		try {
			doc = new SAXReader().read(new File("./src/contact.xml"));
//			Element target = (Element) doc.selectSingleNode("/contactList/contact[@id=1]");
			
			String xpath = "";
			
			//1. 绝对路径
			xpath = "/contactList";
			xpath = "/contactList/contact";
			
			//2. 相对路径
			xpath = "//contact/name";
			xpath = "//name";
			
			//3. 通配符
			xpath = "/contactList/*";	//所有子标签
			xpath = "/contactList//*";	//所有标签
			
			//4. 条件
			xpath = "//contact[@id]";	//选取带 id 属性的 contact 标签
			xpath = "//contact[2]";		//选取第 2 个 contact 标签
			xpath = "//contact[last()]";//选取最后一个
			
			//5. 属性
			xpath = "//@id";	//选取所有带 id 属性的标签
			xpath = "//contact[not(@id)]";	//选取不带 id 属性的 contact 标签
			xpath = "//contact[@id='002']";	//
			xpath = "//contact[@id='001 and @name='李四']";	//
			
			//6. text() 选取文本内容
			xpath = "//name/text()";	//选择文本内容
			xpath = "//name[text()='李四']";
			
			
			List<Node> list = doc.selectNodes(xpath);
			for (Node node : list) {
				System.out.println(node);
			}
			
			
/*			FileOutputStream out = new FileOutputStream(new File("test.xml"));
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			
			XMLWriter writer = new XMLWriter(out, format);
			writer.write(doc);
			writer.close();*/
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
